import { createRouter, createWebHistory } from 'vue-router'

import { useMenuStore } from '@/stores/menuStore'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    //登录注册
    {
      path: '/auth',
      children: [
        {
          path: 'loginpage',
          name: 'LoginPage',
          meta: { title: '登录', public: true },
          component: () => import('@/views/auth/LoginPage.vue')
        },
        {
          path: 'registerpage',
          name: 'RegisterPage',
          meta: { title: '注册', public: true },
          component: () => import('@/views/auth/RegisterPage.vue')
        }
      ]
    },
    //主布局
    {
      path: '/',
      component: () => import('@/components/layout/LayoutView.vue'),
      redirect: '/dashboard/dashboardview',
      children: [
        //首页dashboard
        {
          path: 'dashboard/dashboardview',
          name: 'DashboardView',
          meta: { title: 'Dashboard', requiresAuth: true },
          component: () => import('@/views/dashboard/DashboardView.vue')
        },
        //系统管理
        {
          path: 'system',
          children: [
            //用户管理
            {
              path: 'user',
              children: [
                {
                  path: 'userlist',
                  name: 'UserList',
                  meta: { title: '用户管理' },
                  component: () => import('@/views/system/user/UserList.vue')
                }
              ]
            },
            //角色权限管理
            {
              path: 'role',
              children: [
                {
                  path: 'rolelist',
                  name: 'RoleList',
                  meta: { title: '角色管理' },
                  component: () => import('@/views/system/role/RoleList.vue')
                }
              ]
            },
            //菜单管理
            {
              path: 'menu',
              children: [
                {
                  path: 'menulist',
                  name: 'MenuList',
                  meta: { title: '菜单管理' },
                  component: () => import('@/views/system/menu/MenuList.vue')
                }
              ]
            },
            //权限管理
            {
              path: 'permission',
              children: [
                {
                  path: 'permissionlist',
                  name: 'PermissionList',
                  meta: { title: '权限管理' },
                  component: () => import('@/views/system/permission/PermissionList.vue')
                }
              ]
            }
          ]
        },
        //日志管理
        {
          path: 'log/loglist',
          name: 'OperationLog',
          meta: { title: '日志管理' },
          component: () => import('@/views/system/log/OperationLog.vue')
        },
        //系统设置
        // {
        //   path: 'setupsystem',
        //   name: 'SetupSystem',
        //   meta: { title: '系统设置' },
        //   component: () => import('@/views/system/SetupSystem.vue')
        // },
        //文章管理
        {
          path: 'content/articlelist',
          name: 'ArticleList',
          meta: { title: '文章列表' },
          component: () => import('@/views/content/ArticleList.vue')
        },
        {
          path: 'content/articleadd/:id?',
          name: 'ArticleAddorEdit',
          meta: { title: '文章新增或编辑' },
          component: () => import('@/views/content/ArticleAddorEdit.vue')
        },
        {
          path: 'content/articlecategory',
          name: 'ArticleCategory',
          meta: { title: '文章分类管理' },
          component: () => import('@/views/content/ArticleCategory.vue')
        },
        //文件管理
        {
          path: 'file/filelist',
          name: 'FileList',
          meta: { title: '文件列表' },
          component: () => import('@/views/file/FileList.vue')
        },
        {
          path: 'file/fileupload',
          name: 'FileUpload',
          meta: { title: '文件上传' },
          component: () => import('@/views/file/FileUpload.vue')
        },
        //个人中心
        {
          path: 'profile/profileview',
          name: 'ProfileView',
          meta: { title: '个人中心' },
          component: () => import('@/views/profile/ProfileView.vue')
        }
      ]
    },
  ]
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  const isPublic = to.matched.some(record => record.meta.public)
  const needAuth = to.matched.some(record => record.meta.requiresAuth)

  if (needAuth && !token) {
    // 需要登录但没 token，跳转登录页
    next('/auth/loginpage')
  } else if (token && isPublic) {
    // 已登录还想进登录/注册页，跳转首页
    next('/dashboard/dashboardview')
  } else if (token && needAuth) {
    // 已登录且需要认证的页面，获取用户菜单
    try {
      const menuStore = useMenuStore()
      // 如果还没有获取过用户菜单，则获取
      if (menuStore.userMenuList.length === 0) {
        await menuStore.fetchUserMenuTree()
      }
      next()
    } catch (error) {
      console.error('获取用户菜单失败:', error)
      next()
    }
  } else {
    next()
  }
})
// 全局后置钩子：动态设置标题
router.afterEach((to) => {
  const baseTitle = '后台管理系统'
  document.title = to.meta?.title ? `${to.meta.title} - ${baseTitle}` : baseTitle
})
export default router
